<template>
  <div class="app-container" style="display: flex;">
    <div style="width: 60%;padding-right: 10px">
      <h3>监理日志录入</h3>
      <el-form ref="dataForm" :rules="rules" :model="goods">
        <el-form-item label="项目" prop="status">
          <el-select
            v-model="goods.shopName"
            :disabled="this.$route.query.id || this.$route.query.shopId"
            clearable
            style="width: 200px"
            class="filter-item"
            placeholder="请选择项目"
            @change="selectProductType"
          >
            <el-option v-for="(item,index) in shopList" :key="index" :label="item.shopName" :value="{ value: item.id, label: item.shopName}"/>
          </el-select>
        </el-form-item>
        <el-form-item label="天气" prop="tianqi">
          <el-input v-model="goods.tianqi" />
        </el-form-item>
        <el-form-item label="简介" prop="description">
          <el-input v-model="goods.description" type="textarea" />
        </el-form-item>
        <el-form-item v-if="isBu" label="日志时间" prop="gmtDay">
          <el-col :span="6">
            <el-date-picker
              v-model="goods.gmtDay"
              class="filter-item"
              placeholder="选择时间"
              type="date" />
          </el-col>
        </el-form-item>
      </el-form>
      <el-card class="box-card">
        <h3>工程信息</h3>
        <el-button :plain="true" type="primary" @click="createSkuDialogShow">添加</el-button>
        <el-table :data="skuList">
          <el-table-column property="gongchengPName" label="父工程名称" />
          <el-table-column property="gongchengName" label="子工程名称" />
          <el-table-column property="gongcheng_count" label="工程总量" />
          <el-table-column property="bunit" label="单位" />
          <el-table-column label="今日完成量" property="today_count"/>
          <el-table-column
            align="center"
            label="操作"
            width="180"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="updateSkuDialogShow(scope.row, scope.row.$index)">修改</el-button>
              <el-button type="danger" size="mini" @click="handleSkuDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 添加SKU的Dialog -->
        <el-dialog :visible.sync="skuVisiable" :title="skuStatusDialogMap[skuStatus]">
          <el-form
            ref="skuForm"
            :model="skuForm"
            status-icon
            label-position="left"
            label-width="120px"
            style="width: 400px; margin-left:50px;"
          >
            <el-input v-model="skuForm.id" type="hidden" />

            <el-form-item label="父工程" prop="gongchengPName">
              <el-select
                v-model="skuForm.gongchengPName"
                clearable
                style="width: 200px"
                class="filter-item"
                placeholder="请选择父工程"
                @change="selectProductTypeP"
              >
                <el-option v-for="(item,index) in biaozhunList" :key="index" :label="item.gongchengName" :value="{ value: item.gongchengXuhao, label: item.gongchengName}"/>
              </el-select>
            </el-form-item>
            <el-form-item label="子工程" prop="gongchengName">
              <el-select
                v-model="skuForm.gongchengName"
                clearable
                style="width: 200px"
                class="filter-item"
                placeholder="请选择子工程"
                @change="selectProductTypeS"
              >
                <el-option v-for="(item,index) in biaozhunListSon" :key="index" :label="item.gongchengName" :value="{ value: item.id, label: item.gongchengName}"/>
            </el-select>        </el-form-item>
            <el-form-item label="图片(可空)">
              <el-upload
                ref="upload"
                :action="uploadPath"
                :headers="headers"
                :limit="5"
                :show-file-list="true"
                :file-list="skuForm.imgsList"
                :on-success="handleSkuImgSuccess"
                :on-remove="handleRemove"
                multiple
                accept=".jpg, .jpeg, .png, .gif"
                list-type="picture-card"
              >
                <i slot="default" class="el-icon-plus" />

              </el-upload>
            </el-form-item>
            <el-form-item>
              <div>总量：{{ skuForm.gongcheng_count }}{{ skuForm.bunit }} </div>
              <div>单价：{{ skuForm.gongcheng_price }}</div>

            </el-form-item>
            <el-form-item label="今日完成量" prop="today_count">
              <el-input v-model="skuForm.today_count" />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="closeskuVisiable">取消</el-button>
            <el-button type="primary" @click="handleSkuAdd">确定</el-button>
          </div>
        </el-dialog>
      </el-card>
      <div class="op-container">
        <el-button @click="handleCancel">取消</el-button>
        <el-button v-if="!goods.id" type="primary" @click="handleCreate">保存</el-button>
        <el-button v-if="goods.id" type="primary" @click="handleEdit">更新</el-button>
      </div>
    </div>
    <div v-show="isShow">
      <h3>今日施工记录</h3>
      <el-form :model="gongchengLog">
        <el-form-item label="项目" prop="status">
          <el-input v-model="gongchengLog.shopName" />
        </el-form-item>
        <el-form-item label="记录描述" prop="description">
          <el-input v-model="gongchengLog.description" type="textarea" />
        </el-form-item>
      </el-form>
      <el-card class="box-card">
        <h3>工程信息</h3>
        <el-table :data="gongchengBiaozhunList">
          <el-table-column property="gongchengName" label="工程名称" />
          <el-table-column property="gongchengCode" label="工程编号" />
          <el-table-column property="bunit" label="单位" />
          <el-table-column label="今日完成量" property="today_count"/>
          <el-table-column label="图片" property="imgList">
            <template slot-scope="scope">
              <img v-for="(image, index) in scope.row.imgsList" :src="image.url" :key="index" alt="" width="80">
            </template>

          </el-table-column>

        </el-table>
      </el-card>
      <!--      <div v-if="gongchengLog.status==0" class="op-container">
        <el-button type="primary" @click="handleShenheBohui">驳回</el-button>
        <el-button type="primary" @click="handleShenheTongguo">通过</el-button>

      </div>-->
    </div>

  </div>
</template>

<style>
.el-card {
  margin-bottom: 10px;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.input-new-keyword {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 145px;
  height: 145px;
  display: block;
}
</style>

<script>
import { detailGoods, editGoods, createGoods, detailLogGoods } from '@/api/log'
import { uploadPath } from '@/api/storage'
import Editor from '@tinymce/tinymce-vue'
import { MessageBox } from 'element-ui'
import { getToken } from '@/utils/auth'
import { selectShop } from '@/api/frontutil'
import { listByBiaozhun } from '@/api/shopBiaozhun'
import { getBiaozhunByPId } from '../../api/shopBiaozhun'

export default {
  name: 'GoodsUpsert',
  components: { Editor },
  data() {
    return {
      uploadPath,
      shopList: [],
      isBu: this.$route.query.isBu,
      isShow: false,
      skuForm: { imgsList: [] },
      skuList: [],
      biaozhunList: [],
      biaozhunListSon: [],
      gongchengLog: {},
      gongchengBiaozhunList: [],
      freightList: [],
      imgsFileList: [],
      fileList: [],
      skuVisiable: false,
      skuStatusDialogMap: { 'create': '创建', 'update': '更新' },
      shigong: {},
      goods: {
        imgList: [],

        fileList: [],
        priceRaw: 0,
        type: 2,
        shopId: this.$route.query.shopId,
        shopName: this.$route.query.shopName

      },
      attributeVisiable: false,
      attributeForm: { attribute: '', value: '' },
      attributes: [],
      skuStatus: '',
      rules: {

        title: [
          { required: true, message: '名称不能为空', trigger: 'blur' }
        ]
      }

    }
  },
  computed: {
    headers() {
      return {
        accessToken: getToken()
      }
    }
  },
  created() {
    this.init()
    this.listShop()
  },
  methods: {
    init: function() {
      const goodsId = this.$route.query.id
      if (goodsId) {
        detailGoods(goodsId).then(response => {
          this.goods = Object.assign({}, response.data.data)
          this.skuList = this.goods.biaozhunList
          this.imgsFileList = []
          listByBiaozhun(this.goods.shopId)
            .then(response => {
              this.biaozhunList = response.data.data
            })
            .catch(() => {
            })
          detailLogGoods(this.goods.shopId, 1, null).then(response => {
            this.gongchengLog = response.data.data
            if (this.gongchengLog) { this.isShow = true }
            this.gongchengBiaozhunList = response.data.data.biaozhunList
          }).catch(() => { })
        })
      } else if (this.$route.query.shopId) {
        listByBiaozhun(this.$route.query.shopId)
          .then(response => {
            this.biaozhunList = response.data.data
          })
          .catch(() => {
          })
        detailLogGoods(this.$route.query.shopId, 1, null).then(response => {
          this.gongchengLog = response.data.data
          if (this.gongchengLog) { this.isShow = true }
          this.gongchengBiaozhunList = response.data.data.biaozhunList
        }).catch(() => { })
      }
    },
    listShop() {
      selectShop()
        .then(response => {
          this.shopList = response.data.data
        })
        .catch(() => {
        })
    },
    selectProductType(data) {
      const { value, label } = data
      this.goods.shopName = label
      this.goods.shopId = value
      listByBiaozhun(value)
        .then(response => {
          this.biaozhunList = response.data.data
        })
        .catch(() => {
        })
      detailLogGoods(value, 1, null).then(response => {
        this.gongchengLog = response.data.data
        if (this.gongchengLog) { this.isShow = true }
        this.gongchengBiaozhunList = response.data.data.biaozhunList
      }).catch(() => { })
    },
    selectProductTypeP(data) {
      const { value, label } = data
      this.skuForm.gongchengPName = label
      this.skuForm.gongchengXuhao = value
      getBiaozhunByPId(this.goods.shopId, value)
        .then(response => {
          this.biaozhunListSon = response.data.data
        })
        .catch(() => {
        })
    },
    selectProductTypeS(data) {
      const { value, label } = data
      this.skuForm.gongchengName = label
      this.skuForm.gongchengId = value
      // 从biaozhunListSon获取信息复制给skuForm
      if (this.biaozhunListSon) {
        for (var j = 0; j < this.biaozhunListSon.length; j++) {
          if (this.biaozhunListSon[j].id === value) {
            this.skuForm.bunit = this.biaozhunListSon[j].bunit
            this.skuForm.gongcheng_count = this.biaozhunListSon[j].gongcheng_count
            this.skuForm.gongchengCode = this.biaozhunListSon[j].gongchengCode
            this.skuForm.gongcheng_price = this.biaozhunListSon[j].gongcheng_price
            this.skuForm.gongchengPxuhao = this.biaozhunListSon[j].gongchengPxuhao
            this.skuForm.gongchengXuhao = this.biaozhunListSon[j].gongchengXuhao
            this.skuForm.biaozhunId = this.biaozhunListSon[j].id
          }
        }
      }
    },
    handleCancel: function() {
      var url = '/shopone/log'
      if (this.$route.query.shopId) {
        url = url + '?shopId=' + this.$route.query.shopId + '&shopName=' + this.$route.query.shopName
      }
      this.$router.push({ path: url })
    },
    /* handleShenheBohui: function() {
      freezeOrActivtion(this.gongchengLog.id, 1).then(response => {
        this.gongchengLog.status = 1
        this.$notify.success({
          title: '成功',
          message: '已驳回'
        })
      }).catch(() => { })
    },
    handleShenheTongguo: function() {
      freezeOrActivtion(this.gongchengLog.id, 2).then(response => {
        this.gongchengLog.status = 2
        this.$notify.success({
          title: '成功',
          message: '审核通过'
        })
      }).catch(() => { })
    },*/
    handleCreate: function() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const finalGoods = {
            ...this.goods,
            biaozhunList: this.skuList
          }
          createGoods(finalGoods)
            .then(response => {
              this.$notify.success({
                title: '成功',
                message: '添加成功'
              })
              var url = '/shopone/log'
              if (this.$route.query.shopId) {
                url = url + '?shopId=' + this.$route.query.shopId + '&shopName=' + this.$route.query.shopName
              }
              this.$router.push({ path: url })
            })
            .catch(response => {
              MessageBox.alert('错误：' + response.data.errmsg, '警告', {
                confirmButtonText: '确定',
                type: 'error'
              })
            })
        } else {
          this.$notify.error({
            title: '失败',
            message: '请完善以上表单'
          })
        }
      })
    },
    handleEdit: function() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const finalGoods = {
            ...this.goods,
            biaozhunList: this.skuList
          }
          editGoods(finalGoods)
            .then(response => {
              this.$notify.success({
                title: '成功',
                message: '编辑成功'
              })
              var url = '/shopone/log'
              if (this.$route.query.shopId) {
                url = url + '?shopId=' + this.$route.query.shopId + '&shopName=' + this.$route.query.shopName
              }
              this.$router.push({ path: url })
            })
            .catch(response => {
              MessageBox.alert('错误：' + response.data.errmsg, '警告', {
                confirmButtonText: '确定',
                type: 'error'
              })
            })
        } else {
          this.$notify.error({
            title: '失败',
            message: '请完善表单'
          })
        }
      })
    },
    closeskuVisiable() {
      this.skuVisiable = false
      // this.$set(this.skuList[this.row_select_index], 'colonelLevelList', '')
      this.skuForm = {}
    },
    createSkuDialogShow() {
      this.skuStatus = 'create'
      if (this.$refs.upload) this.$refs.upload.clearFiles()
      this.skuForm = { imgsList: [] }
      this.skuVisiable = true

      // this.$set(this.skuForm, 'barCode', this.get_time_stamp())
      // this.skuForm.colonelLevelList = this.colonelLevelList
    },
    updateSkuDialogShow(row, index) {
      this.skuStatus = 'update'
      this.row_select_index = this.skuList.indexOf(row)
      this.skuForm = Object.assign({}, row)
      if (!this.skuForm.imgsList) {
        this.skuForm.imgsList = []
      }
      this.skuVisiable = true
    },
    handleSkuAdd() {
      this.$refs['skuForm'].validate(valid => {
        if (valid) {
          if (this.skuForm.id) {
            let index = -1
            for (let i = 0; i < this.skuList.length; i++) {
              if (this.skuList[i].id === this.skuForm.id) {
                index = i
              }
            }
            if (index > -1) {
              var temp1 = Object.assign({}, this.skuForm)
              this.skuList.splice(index, 1, temp1)
              this.skuVisiable = false
              this.skuForm = {}
            }
          } else {
            if (this.skuStatus === 'create') {
              debugger
              var temp = Object.assign({}, this.skuForm)
              this.skuList.unshift(temp)
            }
            if (this.skuStatus === 'update') {
              debugger
              const row_select_index = this.row_select_index
              var temp2 = Object.assign({}, this.skuForm)
              // this.skuList.push(temp2)
              this.skuList.splice(row_select_index, 1, temp2)
            }
            this.skuVisiable = false
          }
        }
      })
    },
    handleSkuDelete(row) {
      const index = this.skuList.indexOf(row)
      this.skuList.splice(index, 1)
    },
    handleSkuImgSuccess(response, file, fileList) {
      if (response.errno === 200) {
        debugger
        this.skuForm.imgsList.push({
          name: file.name,
          url: response.url
        })
      }
    },

    handleRemove: function(file, fileList) {
      for (var i = 0; i < this.skuForm.imgsList.length; i++) {
        var url
        if (file.response === undefined) {
          url = file.url
        } else {
          url = file.response.url
        }

        if (this.skuForm.imgsList[i].url === url) {
          this.skuForm.imgsList.splice(i, 1)
        }
      }
    }

  }
}
</script>
